package com.moon.game.util;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.mongodb.Mongo;
import com.moon.game.database.MongoUtil;

public class ProfileConfig {
	private static int profileNum = 1;
	private static Document document = null;
	public static Element root = null;
	public static Element profile = null;
	public static Map<Integer, Mongo> profiles = new HashMap<Integer, Mongo>(); // ProfileServer
	public static void init(String file) throws Exception{
		SAXReader reader = new SAXReader();
		document = reader.read(new File(file));
		root = document.getRootElement();
		if (root == null) {
			throw new Exception("no root node in config");
		}
		profile = root.element("profiles");
		if (profile == null) {
			throw new Exception("no profiles node in config");
		}
		@SuppressWarnings("unchecked")
		List<Element> servers = profile.elements("mongo");
		for (Iterator<Element> it = servers.iterator(); it.hasNext();) {
			Element elm = it.next();
			String ip = elm.attributeValue("host");
			int port = Integer.parseInt(elm.attributeValue("port"));
			profiles.put(Integer.parseInt(elm.attributeValue("id")), MongoUtil.createMongo(ip, port));
		}
	}
	
	/**
	 * 根据编号取ProfileServer
	 * 
	 * @param id
	 * @return
	 */
	public static Mongo getProfile(int id) {
		return profiles.get(id);
	}
	
	/**
	 * profile数量
	 * 
	 * @return
	 */
	public static int getProfileNum() {
		return profileNum;
	}
}
